package com.jar.exercise.多线程.forkjoin.RecursiveAction;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.execute(new MyRecursiveAction(1, 100));
        TimeUnit.SECONDS.sleep(5000);
    }

}

class MyRecursiveAction extends RecursiveAction {

    private int beginNum;
    private int endNum;
    public static final int max = 10;


    public MyRecursiveAction(int beginNum, int endNum) {
        this.beginNum = beginNum;
        this.endNum = endNum;
    }

    @Override
    protected void compute() {
        if (endNum - beginNum <= max) {
            int sum = 0;
            for (int i = beginNum; i <= endNum; i++) {
                sum += i;
            }
            System.out.printf("执行了%d到%d区间的计算，和为：%d\n",beginNum,endNum,sum);
        }
        else {
            MyRecursiveAction first = new MyRecursiveAction(beginNum, (beginNum + endNum) / 2);
            MyRecursiveAction second = new MyRecursiveAction((beginNum + endNum) / 2 + 1, endNum);
            invokeAll(first, second);
        }
    }
}